package com.pengcheng.taskapplication.mvp.view.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.library.BandCardEditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pengcheng.taskapplication.R;
import com.pengcheng.taskapplication.contants.ConstantValue;
import com.pengcheng.taskapplication.model.BankInfoModel;
import com.pengcheng.taskapplication.model.BindCardModel;
import com.pengcheng.taskapplication.model.BindResModel;
import com.pengcheng.taskapplication.model.PayStatusModel;
import com.pengcheng.taskapplication.model.SubscribeOrderListModel;
import com.pengcheng.taskapplication.mvp.presenter.UserPresenterV2;
import com.pengcheng.taskapplication.net.IView;
import com.pengcheng.taskapplication.util.CheckBankCard;
import com.pengcheng.taskapplication.util.PersonIdCardUtil;
import com.pengcheng.taskapplication.util.SPUtils;
import com.pengcheng.taskapplication.util.ToastUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class ApplyBindCard extends BaseActivity implements IView {

    @BindView(R.id.tv_center_title)
    TextView tv_title;
    UserPresenterV2 userPresenterV2;

    @BindView(R.id.ck_select)
    CheckBox checkBox;

    @BindView(R.id.ll_next)
    LinearLayout ll_next;

    @BindView(R.id.bank_card)
    BandCardEditText bandCardEditText;

    @BindView(R.id.et_phone)
    EditText et_phone;

    @BindView(R.id.et_real_name)
    EditText et_real_name;
    @BindView(R.id.et_idcard)
    EditText et_idcard;


    @BindView(R.id.tv_bank_type)
    TextView tv_bank_type;

    BankInfoModel model;

    public boolean flag;
    private String uid;
    private String newtoken;

    @Override
    protected int layoutResID() {
        return R.layout.activity_bind_bank_card;
    }

    @Override
    protected void initData() {
        tv_title.setText("添加银行卡");
        uid = SPUtils.getString(context, ConstantValue.SpType.userid);
        newtoken = SPUtils.getString(context, ConstantValue.SpType.newtoken);
        userPresenterV2=new UserPresenterV2(this);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                switch (compoundButton.getId()){
                    case R.id.ck_select:
                        if(b){
                            flag=true;
                            ll_next.setBackgroundResource(R.drawable.bg_sign);
                        }else{
                            flag=false;
                            ll_next.setBackgroundResource(R.drawable.bg_next_unselect);
                        }
                        break;
                    default:
                        break;
                }
            }
        });

        bandCardEditText.addTextChangedListener(mTextWatcher);
        //上来判断是否设置密码
      //  getStatus(newtoken,uid);
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        private CharSequence temp;
        private int editStart ;
        private int editEnd ;
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            temp = s.toString().replace(" ","");
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
            //          mTextView.setText(s);//将输入的内容实时显示
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            editStart = bandCardEditText.getSelectionStart();
            editEnd = bandCardEditText.getSelectionEnd();
            if (CheckBankCard.checkBankCard(temp.toString())) {
                //如果输入的是正确的银行卡号，则去调用卡号获取银行的基本信息
                getBankInfo(newtoken,uid,temp.toString());

            }
        }
    };

    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        if(actionType.equals(ConstantValue.RequestKey.getBankInfo)){
            model=(BankInfoModel)data;
            tv_bank_type.setText(model.getBankName());
        }

        if(actionType.equals(ConstantValue.RequestKey.bindCard)){
//            BankInfoModel model=(BankInfoModel)data;
//            tv_bank_type.setText(model.getBankName());

            if(code.equals("7015")){
                String bindtxsn=(String)data;
                Intent intent = new Intent(context, SmsCodeActivity.class);
                intent.putExtra("bindtxsn", bindtxsn);
                startActivity(intent);
            }else {
                Gson gson = new Gson();
                Type type = new TypeToken<BindResModel>() {
                }.getType();
                BindResModel resModel = gson.fromJson(gson.toJson(data), type);
                Intent intent = new Intent(context, SmsCodeActivity.class);
                intent.putExtra("bindtxsn", resModel.getBindtxsn());
                startActivity(intent);
            }
            this.finish();
        }

        if(actionType.equals(ConstantValue.RequestKey.getStatus)){
            PayStatusModel model=(PayStatusModel)data;
            if(model.isexistpwd.equals("0")){
                //未设置密码
                Intent intent =new Intent(context,SetPassword.class);
                startActivity(intent);
            }else{
//                //判断当前状态，是否开启免密支付
//                if(model.ispwd.equals("0")){
//                    //当前状态是免密
//                    aSwitch.setChecked(true);
//
//                }else{
//                    //当前没有开启
//                    aSwitch.setChecked(false);
//                }
            }

        }

    }

    @Override
    public void onFailed(String code, String msg) {
        ToastUtils.showShortToast(msg);
    }

    public void getBankInfo(String token,String uid,String accountnumber){
        userPresenterV2.getBankInfo(token,uid,accountnumber,ConstantValue.RequestKey.getBankInfo);
    }

    @OnClick({R.id.img_back,R.id.ll_next,R.id.tv_xieyi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_xieyi:
                Intent intent = new Intent(context, Html5Activity.class);
                intent.putExtra("url","file:///android_asset/QuickPaymentAgreement.html");
                intent.putExtra("title","快捷支付协议");
                startActivity(intent);
                break;
            case R.id.ll_next:
                String bankNum=bandCardEditText.getBankCardText().toString().trim();
                if(bankNum==null||bankNum.length()==0||!CheckBankCard.checkBankCard(bankNum)){
                    ToastUtils.showShortToast("请输入正确的银行卡号");
                    return;
                }

                if(model==null){
                    ToastUtils.showShortToast("拉取银行卡信息异常，请重试");
                    return;
                }


                String idcardStr=et_idcard.getText().toString();
                if(idcardStr==null|| !PersonIdCardUtil.isValidatedAllIdcard(idcardStr)){
                    ToastUtils.showShortToast("请输入正确的身份证号码");
                    return;
                }

                String readNameStr = et_real_name.getText().toString();
                if(readNameStr==null|| readNameStr.length()==0){
                    ToastUtils.showShortToast("请输入账户名称");
                    return;
                }

                String phone=et_phone.getText().toString().trim();
                if(phone==null||phone.length()==0||phone.length()!=11){
                    ToastUtils.showShortToast("请输入正确的手机号");
                    et_phone.requestFocus();
                    return;
                }

                if(!flag){
                    ToastUtils.showShortToast("请勾选《快捷支付协议》");
                    return;
                }
                //绑卡操作 ,身份证号，和银行账户名称待定

                bindingCard(newtoken,uid,"2",model.getCardMediaType(),idcardStr,model.getBankID(),model.getBankName(),readNameStr
                ,bankNum,phone);


                break;
        }
    }

    public void bindingCard(String newtoken,String uid,String channel,String bankcardtype,String credentialnumber,String bankid,String bankname,String bankaccountname,String bankaccountnumber,String bankphonenumber){
            userPresenterV2.bindingCard(newtoken,uid,channel,bankcardtype,credentialnumber,bankid,bankname,bankaccountname,bankaccountnumber,bankphonenumber,ConstantValue.RequestKey.bindCard);
    }


    //checkout 是否设置密码


    public void getStatus(String token,String uid){
        userPresenterV2.getPayStatus(token,uid,ConstantValue.RequestKey.getStatus);
    }

}
